<template>
  <div>
    <Card>
      <vxe-modal
        v-model="addModel"
        :title="'创建账单'"
        width="800"
        min-width="600"
        min-height="300"
        resize
        destroy-on-close
      >
        <template #default>
          <div class="bill-addition">
            <div class="title">账单信息</div>
            <Form :model="billData" :label-width="80" class="bill-info">
              <Row>
                <Col span="12">
                  <FormItem class="bill-info__item" label="缴费公司">
                    <Select v-model="billData.enterpriseId">
                      <Option
                        v-for="(item, key) in enterpriseList"
                        :value="item.value"
                        :key="key"
                        >{{ item.label }}</Option
                      >
                    </Select>
                  </FormItem>
                </Col>
                <Col span="12">
                  <FormItem label="缴费日期" class="bill-info__item">
                    <Row>
                      <Col span="11">
                        <DatePicker
                          type="date"
                          placeholder="选择日期"
                          v-model="billData.chargeDate"
                        ></DatePicker>
                      </Col>
                      <!-- <Col span="2" style="text-align: center">-</Col>
                    <Col span="11">
                      <TimePicker
                        type="time"
                        placeholder="选择时间"
                        v-model="billData.chargeTime"
                      ></TimePicker>
                    </Col> -->
                    </Row>
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span="24">
                  <FormItem label="备注" class="bill-info__item">
                    <Input
                      v-model="billData.remark"
                      type="textarea"
                      :autosize="{ minRows: 2, maxRows: 5 }"
                      placeholder="请输入账单备注..."
                    ></Input>
                  </FormItem>
                </Col>
              </Row>
            </Form>

            <div class="billContents-options">
              <vxe-toolbar>
                <template #buttons>
                  <vxe-button icon="fa fa-plus" @click="addBillContent(-1)"
                    >新增缴费</vxe-button
                  >
                  <vxe-button @click="$refs.addTable.removeCheckboxRow()"
                    >删除选中</vxe-button
                  >
                </template>
              </vxe-toolbar>
            </div>

            <vxe-table
              class="billContents"
              border
              resizable
              show-overflow
              ref="addTable"
              show-footer
              :footer-method="billComtentAddFooter"
              max-height="400"
              :data="billData.billContents"
              :edit-config="{ trigger: 'click', mode: 'row' }"
              emptyText="请创建缴费"
            >
              <vxe-table-column type="checkbox" width="60"></vxe-table-column>
              <vxe-table-column
                type="seq"
                title="序号"
                width="60"
              ></vxe-table-column>
              <vxe-table-column
                field="name"
                title="费用名称"
                :edit-render="{
                  name: '$select',
                  options: typeList,
                  props: { clearable: true },
                }"
              ></vxe-table-column>

              <vxe-table-column
                field="payableAmount"
                title="应付金额"
                :edit-render="{
                  name: '$input',
                  immediate: true,
                  props: { type: 'float', digits: 2 },
                  events: { change: payableChange },
                }"
              ></vxe-table-column>
              <vxe-table-column
                field="reducedAmount"
                title="减免金额"
                :edit-render="{
                  name: '$input',
                  immediate: true,
                  props: { type: 'float', digits: 2 },
                  events: { change: reduceChange },
                }"
              ></vxe-table-column>
              <!-- <vxe-table-column
              field="actualAmount"
              title="实付金额"
              :edit-render="{
                name: '$input',
                props: { type: 'float', digits: 2 },
              }"
            ></vxe-table-column> -->
              <vxe-table-column field="actualAmount" title="实付金额">
                <template #default="{ row }">
                  <span
                    >{{ (row.payableAmount - row.reducedAmount).toFixed(2) }}
                  </span>
                </template>
              </vxe-table-column>
              <vxe-table-column
                field="detail"
                title="明细"
                :edit-render="{ name: 'input', attrs: { type: 'text' } }"
              ></vxe-table-column>
            </vxe-table>

            <div class="billContents-button">
              <Button @click="submit" type="primary">添加</Button>
              <Button @click="addModel = false">取消</Button>
            </div>
          </div>
        </template>
      </vxe-modal>

      <Modal v-model="editModel" title="修改账单信息" width="70">
        <div class="bill-addition">
          <div class="title">账单信息</div>
          <Form :model="editBilldata" :label-width="80" class="bill-info">
            <Row>
              <Col span="12">
                <FormItem class="bill-info__item" label="缴费公司">
                  <Select v-model="editBilldata.enterpriseId">
                    <Option
                      v-for="(item, key) in enterpriseList"
                      :value="item.value"
                      :key="key"
                      >{{ item.label }}</Option
                    >
                  </Select>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="缴费日期" class="bill-info__item">
                  <Row>
                    <Col span="11">
                      <DatePicker
                        type="date"
                        placeholder="选择日期"
                        v-model="editBilldata.chargeDate"
                      ></DatePicker>
                    </Col>
                    <Col span="2" style="text-align: center">-</Col>
                    <Col span="11">
                      <TimePicker
                        type="time"
                        placeholder="选择时间"
                        v-model="editBilldata.chargeTime"
                      ></TimePicker>
                    </Col>
                  </Row>
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span="24">
                <FormItem label="备注" class="bill-info__item">
                  <Input
                    v-model="editBilldata.remark"
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 5 }"
                    placeholder="请输入账单备注..."
                  ></Input>
                </FormItem>
              </Col>
            </Row>
          </Form>

          <div class="billContents-options">
            <vxe-toolbar>
              <template #buttons>
                <vxe-button
                  icon="fa fa-plus"
                  @click="addBillContentToEditTable(-1)"
                  >新增缴费</vxe-button
                >

                <vxe-button @click="$refs.editTable.removeCheckboxRow()"
                  >删除选中</vxe-button
                >
              </template>
            </vxe-toolbar>
          </div>

          <vxe-table
            class="billContents"
            border
            resizable
            show-overflow
            ref="editTable"
            show-footer
            max-height="400"
            :data="editBilldata.billContents"
            :edit-config="{ trigger: 'click', mode: 'cell' }"
            emptyText="请创建缴费"
          >
            <vxe-table-column type="checkbox" width="60"></vxe-table-column>
            <vxe-table-column
              type="seq"
              title="序号"
              width="60"
            ></vxe-table-column>

            <vxe-table-column
              field="name"
              title="费用名称"
              :edit-render="{
                name: 'select',
                options: typeList,
                props: { clearable: true },
              }"
            ></vxe-table-column>
            <vxe-table-column
              field="payableAmount"
              title="应付金额"
              :edit-render="{
                name: '$input',
                props: { type: 'float', digits: 2 },
              }"
            ></vxe-table-column>
            <vxe-table-column
              field="reducedAmount"
              title="减免金额"
              :edit-render="{
                name: '$input',
                props: { type: 'float', digits: 2 },
              }"
            ></vxe-table-column>
            <vxe-table-column field="actualAmount" title="实付金额">
              <template #default="{ row }">
                <span>{{ row.payableAmount - row.reducedAmount }} 元</span>
              </template>
            </vxe-table-column>
          </vxe-table>
        </div>
        <div slot="footer">
          <Button @click="submitEdit" type="primary">添加</Button>
          <Button @click="editModel = false">取消</Button>
        </div>
      </Modal>
      <vxe-grid
        highlight-hover-row
        show-header-overflow
        show-overflow
        ref="xGrid"
        height="600"
        align="center"
        :data="billList"
        :columns="tableColumn"
        :toolbar-config="tableToolbar"
        :edit-config="{
          trigger: 'manual',
          mode: 'row',
          showStatus: true,
          icon: 'fa fa-file-text-o',
        }"
        emptyText="未查询到账单记录"
      >
        <template #form>
          <Form :model="formData" :label-width="70">
            <Row :gutter="16">
              <Col span="6">
                <FormItem label="缴费公司">
                  <Select v-model="formData.enterpriseId">
                    <Option
                      v-for="(item, key) in enterpriseList"
                      :value="item.value"
                      :key="key"
                      >{{ item.label }}</Option
                    >
                  </Select>
                </FormItem>
              </Col>
              <Col span="6">
                <FormItem label="账单号" class="bill-info__item">
                  <Input v-model="formData.billNumber" placeholder=""></Input>
                </FormItem>
              </Col>
              <Col span="6">
                <FormItem label="开始时间">
                  <DatePicker
                    type="date"
                    placeholder="选择日期"
                    v-model="formData.startDate"
                  ></DatePicker>
                </FormItem>
              </Col>
              <Col span="6">
                <FormItem label="结束时间">
                  <DatePicker
                    type="date"
                    placeholder="选择日期"
                    v-model="formData.endDate"
                  ></DatePicker>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </template>
        <template #toolbar_buttons>
          <Button
            type="primary"
            icon="ios-search"
            style="margin-right: 10px"
            @click="queryBill()"
            >查询
          </Button>
          <Button
            type="primary"
            style="margin-right: 10px"
            icon="md-refresh"
            @click="refreshTable()"
            >刷新
          </Button>
          <Button type="primary" style="margin-right: 10px" @click="addBill()"
            >创建账单
          </Button>
          <Button type="error" style="margin-right: 10px" @click="deleteList()"
            >批量删除
          </Button>
        </template>

        <template #contentExpand="{ row }">
          <vxe-grid
            :columns="billContentColumn"
            :data="row.billContents"
            show-footer
            :footer-method="billCountFooter"
            class="billContentTable"
            size="mini"
          ></vxe-grid>
        </template>

        <template #cellExpand="{ row }">
          <span>（{{ row }}）</span>
        </template>
        <!-- <template #operate="{ row }"> -->
        <!-- <Button
            type="primary"
            style="margin-right: 10px"
            @click="editRow(row)"
            >编辑
          </Button>
          <Button
            type="error"
            style="margin-right: 10px"
            @click="deleteRow(row)"
            >删除
          </Button> -->
        <!-- </template> -->
        <template #pager>
          <div style="text-align: center; padding: 10px">
            <Page
              :current="page.current"
              :total="page.total"
              :page-size="page.pageSize"
              show-elevator
              show-total
              show-sizer
              @on-change="refresh"
            />
          </div>
        </template>
      </vxe-grid>
    </Card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      parkId: 0,
      editBilldata: {},

      billData: {
        billContents: [
          // {
          //   name: "",
          //   payableAmount: 0,
          //   reducedAmount: 0,
          //   actualAmount: 0,
          // },
        ],
        payableTotal: 0,
        reducedTotal: 0,
        actualTotal: 0
      },
      submitLoadding: true,
      typeList: [],
      enterpriseList: [],
      value1: 1,

      editModel: false,
      addModel: false,
      parkList: [],
      // enterpriseList: [],
      formData: {
        enterpriseId: '',
        billNumber: '',
        startDate: '',
        endDate: ''
      },
      searchData: {
        startDate: '',
        endDate: ''
      },
      tableToolbar: {
        zoom: true,
        custom: true,
        slots: {
          buttons: 'toolbar_buttons',
          tools: 'toolbar_tools'
        }
      },
      tableColumn: [
        { type: 'checkbox', width: 40, fixed: 'left' },
        {
          type: 'expand',
          width: 40,
          slots: { content: 'contentExpand' },
          fixed: 'left'
        },
        { field: 'billNumber', title: '账单编号' },
        { field: 'enterpriseId', title: '缴费企业' },
        { field: 'chargeDate', title: '创建时间' },
        { field: 'payableTotal', title: '费用总计' },
        { field: 'reducedTotal', title: '减免费用' },
        { field: 'reducedTotal', title: '实付费用' },
        { field: 'remark', title: '备注' }

      ],
      billContentColumn: [
        { field: 'name', title: '账单类型' },
        { field: 'actualAmount', title: '实际费用' },
        { field: 'payableAmount', title: '应交费用' },
        { field: 'reducedAmount', title: '减免费用' },
        { field: 'detail', title: '明细' }
      ],
      page: {
        current: 1,
        total: 0,
        pageSize: 10
      },
      billList: []
    }
  },
  mounted () {
    this.parkId = this.$store.state.user.parkId
    this.queryBill()
    this.getEnterpriseList()
    this.getTypeList()
  },
  methods: {
    billCountFooter ({ columns, data }) {
      const footData = []
      let payableTotal = 0
      let reducedTotal = 0
      const actualTotal = 0
      columns.forEach((column, columnIndex) => {
        switch (columnIndex) {
          case 2:
            payableTotal = this.sumNum(data, column.property)
          case 3:
            reducedTotal = this.sumNum(data, column.property)
          // case 5:
          //   actualTotal = this.sumNum(data, column.property);
        }
      })
      footData.push('合计')
      footData.push((payableTotal - reducedTotal).toFixed(2))
      footData.push(payableTotal)
      footData.push(reducedTotal)

      footData.push('-')
      // 返回一个二维数组的表尾合计
      return [footData]
      const footerDate = [['合计', 'contents.actualTotal', 'contents.payableTotal', 'contents.reducedTotal', '-']]
      return footerDate
    },
    sumNum (list, field) {
      let count = 0
      list.forEach((item) => {
        const rowCount = parseFloat(count)
        count = parseFloat(item[field]) + parseFloat(count)
      })
      return count
    },
    billComtentAddFooter ({ columns, data }) {
      const footData = []
      let payableTotal = 0
      let reducedTotal = 0
      const actualTotal = 0
      columns.forEach((column, columnIndex) => {
        switch (columnIndex) {
          case 3:
            payableTotal = this.sumNum(data, column.property)
          case 4:
            reducedTotal = this.sumNum(data, column.property)
          // case 5:
          //   actualTotal = this.sumNum(data, column.property);
        }
      })
      footData.push('合计')
      footData.push('-')
      footData.push('-')
      footData.push(payableTotal)
      footData.push(reducedTotal)
      footData.push((payableTotal - reducedTotal).toFixed(2))
      // 返回一个二维数组的表尾合计
      return [footData]
    },
    updateAddTableFooter () {
      const $table = this.$refs.addTable
      $table.updateFooter()
    },
    refresh (curPage) {
      this.page.current = curPage
      this.queryBill()
    },
    reduceChange  ({ row }) {
      if (row.reducedAmount > row.payableAmount) {
        this.$Message.error(row.name + ' 减免金额不能大于应付金额')
        row.reducedAmount = row.payableAmount
      }
      if (row.reducedAmount < 0) {
        this.$Message.error(row.name + ' 减免金额不能小于0')
        row.reducedAmount = 0
      }
      this.updateAddTableFooter()
    },
    payableChange  ({ row }) {
      if (row.reducedAmount > row.payableAmount) {
        this.$Message.error(row.name + ' 应付金额不能小于减免金额')
        row.reducedAmount = row.payableAmount
      }
      if (row.payableAmount < 0) {
        this.$Messgae.error(row.name + ' 应付金额不能小于0')
        row.payableAmount = 0
      }
      this.updateAddTableFooter()
    },
    submit () {
      if (this.billData.enterpriseId == null) {
        this.$Message.error('缴费公司不能为空')
        return
      }
      if (this.billData.chargeDate == null) {
        this.$Message.error('请选择缴费日期')
        return
      }

      const $table = this.$refs.addTable
      const fullData = $table.getTableData().fullData

      // if (this.fullData.length == 0) {
      //   this.$Message.error("请输入至少一项缴费项");
      //   return;
      // }
      this.billData.payableTotal = 0
      this.billData.reducedTotal = 0
      this.billData.actualTotal = 0
      fullData.forEach((row) => {
        // if (row.actualAmount == 0) {
        // this.$Message.error(row.name, "缴费项未填写缴费金额");
        //   return;
        // }
        row.actualAmount = (row.payableAmount - row.reducedAmount).toFixed(2)
        this.billData.payableTotal = parseFloat(row.payableAmount) + parseFloat(this.billData.payableTotal)
        this.billData.reducedTotal = parseFloat(row.reducedAmount) + parseFloat(this.billData.reducedTotal)
      })
      this.billData.actualTotal = this.billData.payableTotal - this.billData.reducedTotal
      this.billData.billContents = fullData
      const date = this.billData.chargeDate
      this.billData.chargeDate = this.formatDate(date) + ' ' + '00:00:00'

      this.billData.parkId = this.parkId

      this.submitBill()
      this.addModel = false
    },
    submitEdit  () {
      if (this.editBilldata.enterpriseId == null) {
        this.$Message.error('缴费公司不能为空')
        return
      }
      if (this.editBilldata.chargeDate == null) {
        this.$Message.error('请选择缴费日期')
        return
      }
      if (this.editBilldata.chargeTime == null) {
        this.$Message.error('请选择缴费时间')
        return
      }
      if (this.editBilldata.billContents.length == 0) {
        this.$Message.error('请输入至少一项缴费项')
        return
      }
      // 调用修改账单接口

      this.addModel = false
    },

    reset () { },

    getTypeList () {
      const queryData = {
        parkId: this.parkId
      }
      this.$Axios
        .request({
          method: 'get',
          url: '/bill/bill-type/get',
          params: queryData
        })
        .then((response) => {
          if (response.data.code == 200) {
            const dataList = response.data.msg.billTypes
            for (const i in dataList) {
              this.typeList.push({
                label: dataList[i].name,
                value: dataList[i].name
              })
            }
          } else {
            this.$Message.error(response.data.msg)
          }
        })
    },
    getEnterpriseList  () {
      this.$Axios
        .request({
          method: 'get',
          url: 'enterprise/list/all'
        })
        .then((response) => {
          if (response.data.code == 200) {
            const dataList = response.data.msg
            this.enterpriseList.push({
              label: '全部',
              value: ''
            })
            for (const i in dataList) {
              this.enterpriseList.push({
                label: dataList[i].name,
                value: dataList[i].id
              })
            }
          } else {
            this.$Message.error(response.data.msg)
          }
        })
    },
    formatDate (date) {
      var y = date.getFullYear()
      var m = date.getMonth() + 1
      m = m < 10 ? '0' + m : m
      var d = date.getDate()
      d = d < 10 ? '0' + d : d
      return y + '-' + m + '-' + d
    },
    formatDateTime (date) {
      if (date == '') {
        return ''
      }
      var y = date.getFullYear()
      var m = date.getMonth() + 1
      m = m < 10 ? '0' + m : m
      var d = date.getDate()
      d = d < 10 ? '0' + d : d
      var h = date.getHours()
      h = h < 10 ? '0' + h : h
      var min = date.getMinutes()
      min = min < 10 ? '0' + min : min
      var s = date.getSeconds()
      s = s < 10 ? '0' + s : s
      return y + '-' + m + '-' + d + '  ' + h + ':' + min + ':' + s
    },
    formatBillTime  () {
      this.billList.forEach((bill) => {
        const chargeDate = new Date(bill.chargeDate)
        bill.chargeDate = this.formatDateTime(chargeDate)
      })
    },
    submitBill  () {
      this.$Axios
        .request({
          method: 'post',
          url: '/bill/add',
          data: this.billData
        })
        .then((response) => {
          if (response.data.code == 200) {
            this.$Message.success('创建成功，账单号为' + response.data.msg)
          } else {
            this.$Message.error(response.data.msg)
          }
        })
      this.billData = {
        billContents: []
      }
    },
    async addBillContent (row) {
      const $table = this.$refs.addTable
      const record = {
        name: this.typeList[0].label,
        payableAmount: 0,
        reducedAmount: 0,
        actualAmount: 0
      }
      // this.billData.billContents.push(record);
      const { row: newRow } = await $table.insertAt(record, row)
      await $table.setActiveCell(newRow, 'name')
    },
    async addBillContentToEditTable (row) {
      const $table = this.$refs.editTable
      const record = {
        name: this.typeList[0].label,
        payableAmount: 0,
        reducedAmount: 0,
        actualAmount: 0
      }
      // this.editBilldata.billContents.push(record);
      const { row: newRow } = await $table.insertAt(record, row)
      await $table.setActiveCell(newRow, 'name')
    },
    addBill () {
      this.addModel = true
    },
    queryBill () {
      const billQueryData = {
        pageNum: this.page.current,
        pageSize: this.page.pageSize,
        billNumber: this.formData.billNumber,
        enterpriseId: this.formData.enterpriseId,
        startDate: this.formatDateTime(this.formData.startDate),
        endDate: this.formatDateTime(this.formData.endDate)
      }
      this.$Axios
        .request({
          method: 'post',
          url: '/bill/query',
          data: billQueryData
        })
        .then((response) => {
          if (response.data.code == 200) {
            // this.$Message.success("查询成功");
            if (response.data.state == 'success') {
              this.billList = response.data.msg.data
              this.page.total = response.data.msg.total
              this.formatBillTime()
            } else {
              this.billList = []
            }
          } else {
            this.$Message.error(response.data.msg)
          }
        })
    },
    refreshTable () {
      this.queryBill()
    },
    deleteList  () {
      // 获取选中的数据
      const selectedRecords = this.$refs.xGrid.getCheckboxRecords()
      const billNumbserList = []
      let comfirmString = ''
      for (const i in selectedRecords) {
        billNumbserList.push(selectedRecords[i].billNumber)
        comfirmString += "\n '" + selectedRecords[i].billNumber + "'"
      }
      this.$Modal.confirm({
        title: '操作确认',
        content: '您确定要删除账单' + comfirmString + '吗',
        onOk: () => {
          for (const i in billNumbserList) {
            this.deleteBill(billNumbserList[i])
          }
          //   this.deleteBill( row.billNumber)
        },
        onCancel: () => { }
      })
    },
    editRow (row) {
      const _row = JSON.stringify(row)
      this.editBilldata = JSON.parse(_row)
      this.editModel = true
    },
    deleteRow  (row) {
      this.$Modal.confirm({
        title: '操作确认',
        content: '您确定要删除账单"' + row.billNumber + '"吗',
        onOk: () => {
          this.deleteBill(row.billNumber)
        },
        onCancel: () => { }
      })
    },

    deleteBill (id) {
      const deleteData = {
        billId: id
      }
      this.$Axios
        .request({
          method: 'get',
          url: '/bill/delete',
          params: deleteData
        })
        .then((response) => {
          if (response.data.code == 200) {
            this.$Message.success("删除账单'" + id + "'成功")
          } else {
            this.$Message.error(response.data.msg)
          }
        })
    }
  }
}
</script>
<style scoped>
.bill-addition {
  display: flex;
  flex-direction: column;
  align-content: center;
  padding: 20px 30px;
  background-color: #fff;
}
.title {
  margin: 10px 0px 20px 0px;
  font-size: large;
  font-weight: bold;
}
.billContents {
  width: 100%;
}
.billContentTable {
  margin-right: auto;
  margin-left: 20px;
  width: 50%;
}
.option {
  margin: auto;
  display: flex;
  flex-direction: row;
  justify-content: center;
  margin-top: 10px;
  width: 50%;
}

.billContents-options {
  margin-top: 30px;
}

.billContents-button {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  margin-top: 30px;
  margin-left: 80%;
}
</style>
